package com.mtk.launcher.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.mtk.launcher.config.AppConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static CrashHandler sInstance;

    private CrashHandler() {
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    public static synchronized CrashHandler getInstance() {
        if (sInstance == null) {
            sInstance = new CrashHandler();
        }
        return sInstance;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Log.e(TAG, "Uncaught exception", ex);
        saveCrashInfoToFile(ex);
        // 可以在这里添加上传日志到服务器的逻辑
        // uploadLogToServer();
        // 退出应用
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    private void saveCrashInfoToFile(Throwable ex) {
        TimerDealUtil.getInstance().onDestroyTimer();
        StringBuilder sb = new StringBuilder();
        sb.append("Time: ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("\n");
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
            File fileDir = new File(AppConfig.CRACH_PATH);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            String fileName = "crash_log_" + SimpleDateUtil.getCurrentTimelONG() + ".txt";
            File file = new File(fileDir, fileName);
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.append(sb.toString());
            fileWriter.close();
            Log.e(TAG, "保存成功");
        } catch (IOException e) {
            Log.e(TAG, "保存失败", e);
        }
    }
}
